#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#ifndef __WIN32__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/socket.h>
#include <stdarg.h>
#include <signal.h>
#else

#endif

volatile int gSIGHUP = 0;

typedef int SOCKET;

extern volatile SOCKET gSocket;
void n1server();

#define closesocket(x) close(x);


#define ROOT_FOLDER  "/Users/nes/"

const char* gRootFolder  = ROOT_FOLDER;
const char* gLogFileName = ROOT_FOLDER "n1d.log";

FILE *gLog = stdout;

void n1log(const char* format, ...)
{
  if (!gLog)
  {
    gLog = fopen(gLogFileName, "a+");
    if (!gLog) return;
  }
  va_list argList;
  va_start( argList, format );
  vfprintf(gLog, format, argList);
  time_t t = time(NULL);
  fprintf(gLog, " %s\n", ctime( &t ) );
  fflush(gLog);
  va_end(argList);
}

void n1exit(int code)
{
  if(gLog)
  {
    fclose(gLog);
  }
  if(gSocket)
  {
    closesocket(gSocket);
  }
  exit(code);
}

int main(void) 
{
  n1log("n1d started.");

  if ((chdir("/")) < 0) {
    n1log("chdir(\"/\") returned value < 0.");
    n1exit(EXIT_FAILURE);
  }

  n1server();

  n1log("n1d successfully exit.");
  n1exit(EXIT_SUCCESS);
}
